﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using WCFMINERP.Services.TransferFileServers;
using WCFMINERP.Contracts.DataContracts;
using System.Threading;
using WCFMINERP.Contracts.InterFaces;
using WCFMINERP.COM;
using WCFMINERP.BLL.TransferBLL;
using WCFMINERP.Services.Shop;
using WCFMINERP.Services.Patcher;
using WCFMINERP.Services.Query;
using WCFMINERP.BLL.ShopBLL;
using System.IO;
using System.Net;
using WCFMINERP.BLL.Analyse;
using WCFMINERP.Services.Files;
using WCFMINERP.BLL.PhotoDownload;
using WCFMINERP.Services.LatticePartition;

namespace WCFMINERP.Hosting
{
    public partial class FrmTransferFileManager : Form
    {
        public FrmTransferFileManager()
        {
          
            InitializeComponent();
        }

        private SynchronizationContext _syncContext;
        private ServiceHost _serviceHost;

        int intDoing = (int)TransferStatus.Doing;
        public List<UploadInfo> UploadList = new List<UploadInfo>();
        TransferFilesServiceBLL _bll = new TransferFilesServiceBLL();//上传业务层
        ServiceHost fileTransferHost = new ServiceHost(typeof(TransferFilesService));//上传服务
        ServiceHost shopService = new ServiceHost(typeof(Shop)); //商户开等服务
        ServiceHost patherHost = new ServiceHost(typeof(PatcherServer));//更新服务
        ServiceHost queryHost = new ServiceHost(typeof(InfoQuery));//更新服务
        ServiceHost innerFactoryHost = new ServiceHost(typeof(InnerFactoryServices.InnerFactoryServices));

        ServiceHost productHost = new ServiceHost(typeof(ProductServer));//提供查询商户服务


        FrmAutoOrder frmorder = new FrmAutoOrder();


        ServiceHost orderHost = new ServiceHost(typeof(OrderInfoServer));  //获取订单的服务


        ServiceHost LatticePartitionHost = new ServiceHost(typeof(LatticePartitionServer));  //格子分区服务



        FileSystemWatcher _watcherFile = new FileSystemWatcher();//监控文件夹
        string SavePath=string.Empty;
        
       

        private void FrmTransferFileManager_Load(object sender, EventArgs e)
        {
            try
            {
                try
                {
                    SavePath = _bll.GetSavePath();

                    if (string.IsNullOrEmpty(SavePath))
                    {
                        return;
                    }

                    if (!Directory.Exists(SavePath))
                    {
                        Directory.CreateDirectory(SavePath);
                    }
                    _watcherFile.Path = SavePath;
               
                

                System.Threading.Thread threa = new System.Threading.Thread(AutomaticAcquisition);
                threa.Start();
                }
                catch (Exception ex)
                {
                    //return;
                }
                frmorder.Show();
                UploadList = _bll.GetUploadList((int)TransferStatus.Doing);
                backgroundWorkerFileTransfer.WorkerReportsProgress = true;
                backgroundWorkerFileTransfer.WorkerSupportsCancellation = true;
                backgroundWorkerFileTransfer.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "" + ex.Message);
                MessageBox.Show(ex.Message);
            }
        }


        bool isRun = false;

        /// <summary>
        /// 监视需要自动开单的目录
        /// </summary>
        void AutomaticAcquisition()
        {
            if (!Directory.Exists(SavePath))
            {
                Directory.CreateDirectory(SavePath);
            }
            while (!isRun)
            {
                isRun = !isRun;
                DirectoryInfo folder = new DirectoryInfo(SavePath);   
             
                FileInfo[] files=folder.GetFiles();

                foreach (FileInfo file in files)
                {
                    string filename=file.Name.ToLower();
                    if (filename.EndsWith(".zip") || filename.EndsWith(".rar") || filename.EndsWith(".7z"))
                    {
                        string barcode = file.Name;//.Split('.')[0];  //获取名字，不要后缀
                        UploadQueueInfo info = new UploadQueueInfo();
                        info.FileLength = file.Length;
                        info.ShopId = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["shopId"]);
                        info.ShopName = System.Configuration.ConfigurationSettings.AppSettings["shopName"].ToString();
                        info.Status = (int)TransferStatus.Done;
                        info.ZipName = barcode.Split('.')[0];
                        info.MachineName = Dns.GetHostName();//电脑名
                        info.CreateTime = file.CreationTime;
                        info.ShoptempPath = file.FullName;
                        info.Remark = "";
                        info.orderbagid = 0;
                        try
                        {
                            _bll.Add(info);
                        }
                        catch (Exception ex)
                        {
                            WriteAnalyseLog.WriteLogFile(DateTime.Now + "：添加数据出错" + ex.Message);
                        }
                    }
                }
                isRun = !isRun;
                Thread.Sleep(5000);
            }
        }

        /// <summary>
        /// 监控文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void _watcherFile_Created(object sender, FileSystemEventArgs e)
        {
            string barcode = e.Name;//.Split('.')[0];  //获取名字，不要后缀
            UploadQueueInfo info = new UploadQueueInfo();
            FileInfo fileinfo = new FileInfo(e.FullPath);
            info.FileLength = fileinfo.Length;
            info.ShopId = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["shopId"]);
            info.ShopName = System.Configuration.ConfigurationSettings.AppSettings["shopName"].ToString();
            info.Status = (int)TransferStatus.Done;
            info.ZipName = barcode = e.Name.Split('.')[0];  //获取名字，不要后缀
            info.MachineName = Dns.GetHostName();//电脑名
            info.CreateTime = fileinfo.CreationTime;
            info.ShoptempPath = e.FullPath;
            //info.CompleteTime=dat
            info.Remark = "";
            info.orderbagid = 0;
            
            try
            {
                _bll.Add(info);
            }
            catch (Exception ex)
            {
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动服务时失败" + ex.Message);
            }
        }
               

        void InitFileServer()
        {
            //_syncContext = SynchronizationContext.Current;
            EventMonitor.MonitoringSended += ReceiveMonitoringNotification;
            this.Disposed += delegate
            {
                EventMonitor.MonitoringSended -= ReceiveMonitoringNotification;
                //_serviceHost.Close();
            };
            //fileTransferHost.Opened += delegate
            //{
            //   //this.Text = "下载管理：正在下载";
            //    backgroundWorkerFileTransfer.ReportProgress(0, "下载管理：正在下载");
            //};
            try
            {
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:服务开始启动");

                fileTransferHost.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:传输文件服务启动");
                patherHost.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:更新服务启动");
                shopService.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:开单服务启动");
                queryHost.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:查询服务启动");
                innerFactoryHost.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:工厂服务启动");
                productHost.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:获取商户信息服务启动");

                orderHost.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:获取订单的服务启动");


                LatticePartitionHost.Open();
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:格子分区的服务启动");

                queryHost.Opened += delegate
                {
                    buttonQueryControl.Text = "关闭查询服务";
                };
                //fileTransferHost.
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动:服务启动结束");
            }       
            catch (Exception ex)
            {
                WriteAnalyseLog.WriteLogFile(DateTime.Now + "系统启动服务时失败" + ex.Message);
            }

        }
        public void ReceiveMonitoringNotification(object sender, MonitorEventArgs args)
        {
            UploadInfo inInfo = (UploadInfo)args.args;
            UploadInfo loadinfo = UploadList.FirstOrDefault(lo => lo.ZipName == inInfo.ZipName);
            if (loadinfo == null)
            {
                UploadList.Add(inInfo);
            }
            else
            {
                loadinfo.LastGuage = loadinfo.Guage;
                loadinfo.LastTime = loadinfo.SaveTime;
                loadinfo.Guage = inInfo.Guage;
                loadinfo.SaveTime = inInfo.SaveTime;
                //loadinfo.FileLength = inInfo.FileLength;
                if (inInfo.Status == (int)TransferStatus.Done)
                {
                    UploadList.Remove(loadinfo);
                }
            }
           
            List<UploadInfo> doingList= UploadList.Where(st=>st.Status==intDoing).ToList();

            RushUpdingData(doingList);
 
        }
        //注册刷新方法
        public delegate void rushData( List<UploadInfo> list);
        public void RushUpdingData(List<UploadInfo> list)
        {
            try
            {
                if (gridControlUploading.InvokeRequired)
                {
                    this.Invoke(new rushData(RushUpdingData), new object[] { list });
                    return;
                }
                else
                {
                    gridControlUploading.DataSource = list;
                    gridControlUploading.RefreshDataSource();
                }
            }
            catch { }
        }
        private void backgroundWorkerFileTransfer_DoWork(object sender, DoWorkEventArgs e)
        {
            InitFileServer();

        }

        private void backgroundWorkerFileTransfer_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
           int p= e.ProgressPercentage;
           if (p == 0)
           {
               this.Text = (string)e.UserState;
           }
        }

        private void backgroundWorkerFileTransfer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void gridViewUploading_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            //if (e.RowHandle >= 0)
            //{
            //    if (e.Column.Name == "gridColumn7")
            //    {
            //        int status = (int)e.CellValue;
            //        switch (status)
            //        {
            //            case (int)TransferStatus.Wait:
            //                e.DisplayText = "准备上传";
            //                break;
            //            case (int)TransferStatus.Doing:
            //                e.DisplayText = "正在上传";
            //                break;
            //            case (int)TransferStatus.Done:
            //                e.DisplayText = "完成";
            //                break;
            //            default:
            //                e.DisplayText = "完成";

            //        }
            //    }
            //}
        }

        private void tabControlUnUpload_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlUnUpload.SelectedIndex == 1)//等待列表
            {
                //TransferFilesServiceBLL _bll = new TransferFilesServiceBLL();
                int unLooad = (int)TransferStatus.Wait;
                gridControlUnUpload.DataSource = _bll.GetUploadList(unLooad);
                gridControlUnUpload.RefreshDataSource();

            }
            else if (tabControlUnUpload.SelectedIndex == 2)
            {
                //TransferFilesServiceBLL _bll = new TransferFilesServiceBLL();
                gridControlDone.DataSource = _bll.GetUploadList((int)TransferStatus.Done);
                gridControlDone.RefreshDataSource();
            }
        }

        private void timerRushWaitAnlyse_Tick(object sender, EventArgs e)
        {
            gridControlDone.DataSource = _bll.GetUploadList((int)TransferStatus.Done);
            gridControlDone.RefreshDataSource();
        }

        private void FrmTransferFileManager_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                
                    e.Cancel = true;
                    this.Hide();
             }
        }

        private void DownLoadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void AutoOrderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmorder.Show();
        }

        private void ExitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("这是服务器程序，确定退出吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
            {
                notifyIcon1.Visible = false;
                //frmorder.notifyIcon1.Visible = false;
                Environment.Exit(0);
            }
        }

        private void buttonQueryControl_Click(object sender, EventArgs e)
        {
           
                if (queryHost.State == CommunicationState.Opened)
                {
                    queryHost.Close();
                    queryHost.Closed += delegate
                    {
                        buttonQueryControl.Text = "开启查询服务";
                    };
                }
                else if (queryHost.State == CommunicationState.Closed)
                {
                    queryHost.Open();
                    queryHost.Closed += delegate
                    {
                        buttonQueryControl.Text = "关闭查询服务";
                    };
                }
            
        }

        
    }
}
